package com.tianma315.admin.material.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.tianma315.admin.common.base.CoreServiceImpl;
import com.tianma315.admin.common.exception.MessageException;
import com.tianma315.admin.material.VO.PackingMaterialVO;
import com.tianma315.admin.supplier.domain.SupplierDO;
import com.tianma315.admin.supplier.service.SupplierService;
import com.tianma315.admin.util.CellUtil;
import com.tianma315.admin.util.HiddenSheetUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tianma315.admin.material.dao.PackingMaterialDao;
import com.tianma315.admin.material.domain.PackingMaterialDO;
import com.tianma315.admin.material.service.PackingMaterialService;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 
 * <pre>
 * 包装材料入库记录
 * </pre>
 * <small> 2019-12-23 15:12:33 | Aron</small>
 */
@Service
public class PackingMaterialServiceImpl extends CoreServiceImpl<PackingMaterialDao, PackingMaterialDO> implements PackingMaterialService {
    @Autowired
    PackingMaterialDao packingMaterialDao;
    @Autowired
    SupplierService supplierService;

    @Override
    public Page<PackingMaterialVO> getPackingMaterialVOPage(Integer pageNumber, Integer pageSize, PackingMaterialDO packingMaterialDTO) {
        Page<PackingMaterialVO> page = new Page(pageNumber,pageSize);
        List<PackingMaterialVO> packingMaterialVOList = packingMaterialDao.getpackingMaterialVO(page,packingMaterialDTO);
        page.setRecords(packingMaterialVOList);
        return page;
    }

    @Override
    public boolean deletePackingMaterialById(Integer packingId) {
        PackingMaterialDO packingMaterialDO = new PackingMaterialDO();
        packingMaterialDO.setState(1);
        packingMaterialDO.setPackingId(packingId);
        return updateById(packingMaterialDO);
    }

    @Override
    public HSSFWorkbook exportPackingMaterial() {
        String[] title = {"名称","批次","规格","数量","单位","供应商","入库日期(例:2019/08/08)"};
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("包装材料进库记录模板");

        sheet.addMergedRegion(new CellRangeAddress(0,0,0,6));//第一行第一列开始，跨8列
        sheet.setColumnWidth(6,8 * 512);
        HSSFRow titleRow = sheet.createRow(0);//第0行

        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short)18);
        titleStyle.setFont(font);

        //生成标题
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("包装材料进库记录模板(所有必填)");
        titleCell.setCellStyle(titleStyle);

        //红色字体
        HSSFCellStyle redStyle = wb.createCellStyle();
        redStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont redFont = wb.createFont();
        redFont.setBold(true);
        redFont.setColor(Font.COLOR_RED);
        redStyle.setFont(redFont);

        //默认字体样式
        HSSFCellStyle defaultStyle = wb.createCellStyle();
        defaultStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont defaultFont = wb.createFont();
        defaultFont.setBold(true);
        defaultStyle.setFont(defaultFont);

        //声明列对象
        HSSFCell cell = null;
        //创建表头
        HSSFRow headRow = sheet.createRow(1);
        for(int i=0;i<title.length;i++){
                cell = headRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(redStyle);
        }

        List<SupplierDO> supplierDOS = supplierService.getSupplierList();
        List<String> supplierList = supplierDOS.stream().map(item -> item.getSupplierName()).collect(Collectors.toList());
        String[] supplierListNameArr = supplierList.toArray(new String[supplierList.size()]);


        String supplierHiddenSheet = "supplierHidden";
        Integer supplierCellNum = 5;
        Integer supplierStartRow = 2; // 开始行
        Integer supplierEndRow = 10000; // 结束行
        HiddenSheetUtil.initHiddenSheet(supplierHiddenSheet,wb,supplierCellNum,supplierStartRow,supplierEndRow,supplierListNameArr);
        //设置设备类型为下拉框选项
        DVConstraint supplierConstraint = DVConstraint.createFormulaListConstraint(supplierHiddenSheet);
        CellRangeAddressList supplierRegions = new CellRangeAddressList(supplierStartRow,
                supplierEndRow, supplierCellNum, supplierCellNum);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
//        CellRangeAddressList supplierRegions = new CellRangeAddressList(2,
//                10000, 5, 5);
        HSSFDataValidation supplierData = new HSSFDataValidation(
                supplierRegions, supplierConstraint);
        sheet.addValidationData(supplierData);
        wb.setSheetHidden(1, true);
        return wb;
    }

    @Override
    public void importPackingMaterialImport(MultipartFile file, Long userId) {
        Boolean flag = CellUtil.isExcel(file.getOriginalFilename());
        if (!flag){
            throw new MessageException("只支持Excel文件");
        }

        List<SupplierDO> supplierDOList = supplierService.getSupplierList();

        try {
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum(); //返回行数下标 从0开始
            //前两行都不是内容，所以从2开始
            for (int i = 2; i <= rowNum; i++) {
                Row row = sheet.getRow(i);
                short num = row.getLastCellNum();

                PackingMaterialDO packingMaterialDO = new PackingMaterialDO();
                packingMaterialDO.setCreateBy(userId);
                packingMaterialDO.setCreateDate(Calendar.getInstance().getTime());
                packingMaterialDO.setState(0);

                Cell packingNameCell = row.getCell(0);
                if (CellUtil.isCellEmpty(packingNameCell)){
                    throw new MessageException("名称不能为空");
                }
                packingMaterialDO.setPackingName(packingNameCell.getStringCellValue());

                Cell batchCell = row.getCell(1);
                if (CellUtil.isCellEmpty(batchCell)){
                    throw new MessageException("批次不能为空");
                }
                packingMaterialDO.setBatch(batchCell.getStringCellValue());

                Cell specsCell = row.getCell(2);
                if (CellUtil.isCellEmpty(specsCell)){
                    throw new MessageException("规格不能为空");
                }
                packingMaterialDO.setSpecs(specsCell.getStringCellValue());

                Cell numberCell = row.getCell(3);
                if (CellUtil.isCellEmpty(numberCell)){
                    throw new MessageException("数量不能为空");
                }
                packingMaterialDO.setNumber(Integer.parseInt(numberCell.getStringCellValue()));

                Cell unitCell = row.getCell(4);
                if (CellUtil.isCellEmpty(unitCell)){
                    throw new MessageException("单位不能为空");
                }
                packingMaterialDO.setUnit(unitCell.getStringCellValue());


                //设置供应商
                Cell supplierCell = row.getCell(5);
                if (CellUtil.isCellEmpty(supplierCell)){
                    throw new MessageException("供应商不能空");
                }
                List<SupplierDO> supplierFilterResult = supplierDOList.stream()
                        .filter(item -> item.getSupplierName().equals(supplierCell.getStringCellValue()))
                        .collect(Collectors.toList());
                packingMaterialDO.setSupplierId(supplierFilterResult.get(0).getSupplierId());

                //设置入库日期
                Cell inStockDateCell = row.getCell(6);
                if (inStockDateCell==null){
                    throw new MessageException("入库日期不能为空");
                }
                packingMaterialDO.setInStockDate(inStockDateCell.getDateCellValue());

                insert(packingMaterialDO);

            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}
